package com.lframework.xingyun.basedata.impl.product;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.lframework.starter.web.core.annotations.oplog.OpLog;
import com.lframework.starter.web.core.impl.BaseMpServiceImpl;
import java.io.Serializable;

import com.lframework.starter.web.core.utils.OpLogUtil;
import com.lframework.starter.web.inner.components.oplog.OtherOpLogType;
import com.lframework.xingyun.basedata.entity.Product;
import com.lframework.xingyun.basedata.entity.ProductAssistantUnit;
import com.lframework.xingyun.basedata.entity.ProductPurchase;
import com.lframework.xingyun.basedata.mappers.ProductAssistantUnitMapper;
import com.lframework.xingyun.basedata.service.product.ProductAssistantUnitService;
import com.lframework.xingyun.basedata.service.product.ProductPurchaseService;
import com.lframework.xingyun.basedata.service.product.ProductService;
import com.lframework.xingyun.basedata.vo.product.unit.ProductAssistantUnitVo;
import com.lframework.xingyun.basedata.vo.product.unit.QueryProductAssistantUnitVo;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

@Service
public class ProductAssistantUnitServiceImpl extends BaseMpServiceImpl<ProductAssistantUnitMapper, ProductAssistantUnit> implements ProductAssistantUnitService {


    @Override
    public List<ProductAssistantUnit> query(QueryProductAssistantUnitVo vo) {

        return getBaseMapper().query(vo);
    }

    @Cacheable(value = ProductAssistantUnit.CACHE_NAME, key = "@cacheVariables.tenantId() + #id", unless = "#result == null")
    @Override
    public ProductAssistantUnit findById(String id) {

        return getBaseMapper().selectById(id);
    }

    @Override
    public List<ProductAssistantUnit> queryByProductId(String productId) {
        return getBaseMapper().queryByProductId(productId);
    }

    @OpLog(type = OtherOpLogType.class, name = "保存商品辅助单位，productId：{}", params = {"#productId"})
    @Override
    public void save(String productId, List<ProductAssistantUnitVo> vo) {

        getThis(ProductAssistantUnitService.class).remove(Wrappers.lambdaUpdate(ProductAssistantUnit.class)
                .eq(ProductAssistantUnit::getProductId, productId));

        List<ProductAssistantUnit> list = new ArrayList<>();
        for (ProductAssistantUnitVo productAssistantUnitVo : vo) {
            ProductAssistantUnit productAssistantUnit = new ProductAssistantUnit();
            productAssistantUnit.setProductId(productId);
            productAssistantUnit.setAssistantUnitId(productAssistantUnitVo.getAssistantUnitId());
            productAssistantUnit.setToUnitId(productAssistantUnitVo.getToUnitId());
            productAssistantUnit.setUnitVal(productAssistantUnitVo.getUnitVal());
            list.add(productAssistantUnit);
        }

        getThis(ProductAssistantUnitService.class).saveBatch(list);

        OpLogUtil.setVariable("productId", productId);
        OpLogUtil.setExtra(vo);
    }

    @Override
    public List<ProductAssistantUnit> queryByCodeAndSkuCode(String code, String skuCode) {
        return Collections.emptyList();
    }

    public Integer calcDecomposeNum(String productId, String unitId, String targetUnitId, BigDecimal num) {
        List<ProductAssistantUnit> productAssistantUnits = queryByProductId(productId);
        List<BigDecimal> productUnitVal = new ArrayList<>();
        ProductAssistantUnit productAssistantUnit;
        do {
            String finalTargetUnitId = targetUnitId;
            productAssistantUnit = productAssistantUnits.stream()
                    .filter(item -> StrUtil.equals(item.getToUnitId(), finalTargetUnitId))
                    .findFirst()
                    .orElse(null);
            if (Objects.nonNull(productAssistantUnit)) {
                productUnitVal.add(productAssistantUnit.getUnitVal());
                if (StrUtil.equals(productAssistantUnit.getAssistantUnitId(), unitId)) {
                    productAssistantUnit = null;
                } else {
                    targetUnitId = productAssistantUnit.getAssistantUnitId();
                }
            }
        } while (Objects.nonNull(productAssistantUnit));

        BigDecimal res = num.divide(productUnitVal.stream().reduce(BigDecimal.ONE, BigDecimal::multiply), 6, RoundingMode.HALF_UP);

        return (int) Math.ceil(res.doubleValue());
    }


    /**
     * 计算商品某单位的采购价
     * @param productId
     * @param unitId
     * @return
     */
    @Override
    public BigDecimal calcUnitPurchasePrice(String productId, String unitId) {
        String targetUnitId = unitId;
        Product product = getThis(ProductService.class).findById(productId);
        String baseUnit = product.getUnit();
        ProductPurchase productPurchase = getThis(ProductPurchaseService.class).getById(product.getId());
        List<ProductAssistantUnit> productAssistantUnits = queryByProductId(productId);
        List<BigDecimal> productUnitPrices = new ArrayList<>();
        ProductAssistantUnit productAssistantUnit;
        do {
            String finalTargetUnitId = targetUnitId;
            productAssistantUnit = productAssistantUnits.stream()
                    .filter(item -> StrUtil.equals(item.getToUnitId(), finalTargetUnitId))
                    .findFirst()
                    .orElse(null);
            if (Objects.nonNull(productAssistantUnit)) {
                productUnitPrices.add(productAssistantUnit.getUnitVal());
                if (StrUtil.equals(productAssistantUnit.getAssistantUnitId(), baseUnit)) {
                    productAssistantUnit = null;
                } else {
                    targetUnitId = productAssistantUnit.getAssistantUnitId();
                }
            }
        } while (Objects.nonNull(productAssistantUnit));

        BigDecimal unitPurchasePrice = productPurchase.getPrice();
        for (BigDecimal productUnitPrice : productUnitPrices) {
            unitPurchasePrice = unitPurchasePrice.divide(productUnitPrice, 6, RoundingMode.HALF_UP);
        }
        return unitPurchasePrice;
    }

    @CacheEvict(value = ProductAssistantUnit.CACHE_NAME, key = "@cacheVariables.tenantId() + #key")
    @Override
    public void cleanCacheByKey(Serializable key) {

    }
}

